package com.asiainfo.integration.actions;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;

/**
 * Usage:
 *
 * @author Charkey
 * @date 2015/12/17
 */
@WebServlet(urlPatterns = "/rest/test", asyncSupported = true)
public class RestTestAction extends HttpServlet {

    public static final Logger INFO_LOG = Logger.getLogger(RestTestAction.class);

    private static Client client = null;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        long requestStartTime = 0L;

        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);


        String resource_url = multipartRequest.getParameter("resource_url").trim();
        String routing_zone_id = multipartRequest.getParameter("routing_zone_id").trim();
        String connection_timeout = multipartRequest.getParameter("connection_timeout").trim();
        String read_timeout = multipartRequest.getParameter("read_timeout").trim();
        String directCallCRMServiceFlag = multipartRequest.getParameter("direct_call_crm_service");
        String serviceCode = "";
        if (directCallCRMServiceFlag != null && "on".equals(directCallCRMServiceFlag)) {
            serviceCode = multipartRequest.getParameter("service_code");
        }

        String request_message = null;

        if (connection_timeout.isEmpty()) {
            connection_timeout = "60000";
        }
        if (read_timeout.isEmpty()) {
            read_timeout = "60000";
        }

        request.setAttribute("resource_url", resource_url);
        request.setAttribute("routing_zone_id", routing_zone_id);
        request.setAttribute("connection_timeout", "60000");
        request.setAttribute("read_timeout", "60000");

        MultipartFile request_msg = multipartRequest.getFile("request_message");

        if (request_msg != null) {
            request_message = IOUtils.toString(request_msg.getInputStream());
        }

        String responseMsg = "";
        if (client == null) {
            client = Client.create();
            client.setConnectTimeout(Integer.parseInt(connection_timeout));
            client.setReadTimeout(Integer.parseInt(read_timeout));
        }
        WebResource r = client.resource(resource_url);
        MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
        if (directCallCRMServiceFlag != null && "on".equals(directCallCRMServiceFlag)) {
            formData.add("WEB_HUB_PARAMS", request_message);
            formData.add("servicecode", serviceCode);
        } else {
            formData.add("msg", request_message);
            if (!routing_zone_id.isEmpty()) {
                formData.add("RoutingZoneId", routing_zone_id);
            }
        }
        try {
            requestStartTime = System.currentTimeMillis();
            responseMsg = r.type("application/x-www-form-urlencoded").post(String.class, formData);
            long processTime = System.currentTimeMillis() - requestStartTime;
            request.setAttribute("process_time", processTime + "ms");
            request.setAttribute("error_message", responseMsg);
            request.setAttribute("is_error", false);
            request.getRequestDispatcher("/WEB-INF/pages/rest_test.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            long processTime = System.currentTimeMillis() - requestStartTime;
            request.setAttribute("process_time", processTime + "ms");
            request.setAttribute("error_message", e.getMessage());
            request.setAttribute("is_error", true);
            request.getRequestDispatcher("/WEB-INF/pages/rest_test.jsp").forward(request, response);
        }

    }

}
